package com.shanghaionstar.home;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.onstar.cn.auth.userProfile.Vehicle;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.common.util.EncryptUtil;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.common.CustomLayoutsGroup;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BaseFragment;
import com.onstar.cn.framework.mvp.base.core.BaseFragmentActivity;
import com.onstar.cn.mag.enumtype.PackageType;
import com.onstar.cn.mag.publicService.response.ResponBannerEntity;
import com.onstar.cn.rxconstants.RxConstants;
import com.onstar.cn.smart.BaseResponse;
import com.onstar.cn.smart.entity.ServiceItem;
import com.onstar.cn.sqlite.entities.UserAddressEntity;
import com.onstar.cn.weight.CustomImageView;
import com.onstar.cn.weight.DriveScoreView;
import com.onstar.cn.weight.FuelMeterView;
import com.onstar.cn.weight.HomeBallView;
import com.onstar.cn.weight.ToastView;
import com.onstar.cn.weight.discover.ItemViewData;
import com.onstar.cn.weight.ptr.PtrDefaultHandler;
import com.onstar.cn.weight.ptr.PtrFrameLayout;
import com.onstar.cn.weight.ptr.PtrHandler;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.MainTabActivity;
import com.shanghaionstar.activity.webview.handler.CommonWebViewActivity;
import com.shanghaionstar.activity.webview.handler.DriverBehaviorWebHandler;
import com.shanghaionstar.activity.webview.handler.IWebType;
import com.shanghaionstar.activity.webview.handler.ShareReportWebHandler;
import com.shanghaionstar.activity.webview.handler.UploadPicWebHandler;
import com.shanghaionstar.activity.webview.handler.WebDataEntity;
import com.shanghaionstar.carmanage.CarManageActivity;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.home.iview.IHomeView;
import com.shanghaionstar.home.model.DrivingScore;
import com.shanghaionstar.home.model.HomeModel;
import com.shanghaionstar.home.presenter.DataRefreshPresenter;
import com.shanghaionstar.home.presenter.HomePresenter;
import com.shanghaionstar.home.util.FloatingUtil;
import com.shanghaionstar.iview.ILoginAndOutListener;
import com.shanghaionstar.iview.ILoginListener;
import com.shanghaionstar.navi.NavSearchActivity;
import com.shanghaionstar.test.LoginActivity;
import com.shanghaionstar.login.register.JoinMeUtils;
import com.shanghaionstar.mro.CarStatusActivity;
import com.shanghaionstar.mro.MrOActivity;
import com.shanghaionstar.nav.NavActivity;
import com.shanghaionstar.notification.bean.NotificationConstants;
import com.shanghaionstar.report.bean.ReportReqParam;
import com.shanghaionstar.sqlite.UserAddressInfoImpl;
import com.shanghaionstar.user.iview.IOptViewImpl;
import com.shanghaionstar.user.presenter.OptPresenter;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.FinalConfigParams;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.JoinMeConstants;
import com.shanghaionstar.utils.LoginUtil;
import com.shanghaionstar.utils.MyActivityManager;
import com.shanghaionstar.utils.NotificationUtil;
import com.shanghaionstar.vehicle_ownerlife.VehicleInspectionManager;
import com.shanghaionstar.weight.AgreementDialog;
import com.shanghaionstar.weight.CarAssessAgreementDialog;
import com.shanghaionstar.weight.OnStarPtrHeader;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

import static com.shanghaionstar.OnstarApplication.getApplication;
import static com.shanghaionstar.activity.webview.handler.IWebType.TYPE_SHARE_REPORT;
import static com.shanghaionstar.login.service.LoginTransformHelper.CACHE_STATE_NOCACHE;

/**
 * Created by 6335yz on 2016/1/19.
 */

public class HomeFragment extends BaseFragment implements View.OnClickListener, IHomeView, ILoginListener, ILoginAndOutListener {

    private ProgressDialog dialog;
    /***
     * 刷新layout
     ***/
//    @FindViewById
//    private SuperSwipeRefreshLayout refreshLayout;
    /*******
     * 刷新动画
     ******/
//    private AnimationDrawable animationDrawable;
    @FindViewById
    private PtrFrameLayout ptrFrameLayout;

    private List<BannerBean> initBean = new ArrayList<>();

    @Override
    public int getLayoutId() {
        return R.layout.tab_fragment_home;
    }

    @FindViewById
    private FuelMeterView fuel_meter;
    @FindViewById
    private DriveScoreView driver_score;

    @FindViewById
    private HomeBallView ball;
    @FindViewById
    private TextView car_info_text_id, ubi_tv;
    @FindViewById
    private LinearLayout ubi_ll;
    @FindViewById
    private ImageButton ubi_ib;

//    @FindViewById
//    private BounceScrollView home_bsv;

    @FindViewById
    private TextView tv_oil_value, tv_mile_value, tv_update_time, tv_update;
    private DataRefreshPresenter dataRefreshPresenter;
    private Subscription loginSubscription;
    @FindViewById
    private ImageButton my_trip, my_car;
    @FindViewById
    private ImageButton car_evaluate_ib;
    @FindViewById
    private ImageButton btn__preferential_main;
    //    @FindViewById
//    private ImageButton car_manage;
    @FindViewById
    private LinearLayout update_time, home_hot_key_layout;
    private HomePresenter presenter;
    @FindViewById
    private HomeMrOLayout main_container;
    @FindViewById
    private ImageCycleView banner_view;
    @FindViewById
    private CustomImageView banner_iv;
    @FindViewById
    private RelativeLayout banner_linear;
    @FindViewById
    private LinearLayout dot_layout;

    @FindViewById
    private LinearLayout home_service_btn;
    @FindViewById
    private TextView tv_fuel;

    private String className;
    @FindViewById
    private TextView tv_service;

    @FindViewById
    private View driver_access, fuel_range;


    private FloatingUtil floatingUtil;

    public void showAppFrontNavCommandFailToast(final Action1 action) {
        new ToastView(baseActivity).toast(getString(R.string.send_to_tbt_failed), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Observable.create(new Observable.OnSubscribe<Object>() {
                    @Override
                    public void call(Subscriber<? super Object> subscriber) {
                        subscriber.onNext(new Object());
                    }
                }).subscribe(action);
            }
        });
    }

    @OnClick({R.id.ball, R.id.my_trip, R.id.btn__preferential_main, R.id.tv_update, R.id.my_car, R.id.driver_score, R.id.car_evaluate_ib, R.id.home_service_btn, R.id.ubi_ib, R.id.ubi_tv, R.id.driver_access, R.id.fuel_range})
    @Override
    public void onClick(View v) {
        Bundle bundle = new Bundle();
        switch (v.getId()) {
            case R.id.ball:
//                BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Home_LoginRegister.getStringValue());
//                startActivity(new Intent(getActivity(), LoginActivity.class));
                break;
            case R.id.my_trip:

                BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Home_MyTrip.getStringValue());
                startActivity(new Intent(getActivity(), NavSearchActivity.class));
                break;
            case R.id.btn__preferential_main:
//                Intent intent = new Intent(getActivity(),CheYinWebActivity.class);
//                intent.putExtra("url","http://121.43.188.184:15889/driverservice/home/index?source=onstar&business_type=trafficTicket&signature=4e09471e7fe8723fb9a3afa7cf94fb17286cdde2619846f0a0b243037cc150c2");
//                startActivity(intent);

//                BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Home_MyPrivilege.getStringValue());
                BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Home_OwnersLife.getStringValue());
                startActivity(new Intent(getActivity(), NavActivity.class));
                break;
            case R.id.tv_update:
                break;
            case R.id.ubi_tv:
                launchToWeb();
                break;
            case R.id.ubi_ib:
                ubiAnimate();
                break;
            case R.id.my_car:
                bundle = new Bundle();
                bundle.putString("className", CarManageActivity.class.getName());
                bundle.putString("topTitle", "my_car");
                new LoginUtil().loginAndActionCallBack(baseActivity, RxConstants.HOME_PAGE, this, bundle);
                BusinessUtil.sendReportByClickType(baseActivity, FunctionNameFindId.Home_CarManagement.getStringValue());
                //                startActivity(new Intent(baseActivity, CarManageActivity.class));
                //                Intent it = new Intent(baseActivity, ChargingPileActivity.class);
                //                it.putExtra(FinalConstants.JUMP_FLAG, ChargingPileListFragment.class.getName());
                //                startActivity(it);
                break;
            case R.id.driver_score:
                //                if (ApplicationUtil.getInstance().isGen10()) {
               /* Intent intent = new Intent(baseActivity, CommonWebViewActivity.class);
                intent.putExtra("linkUrl", "https://idt1.onstar.com.cn/mweb/mweb-main/static/OnStar-MA7.0-h5/html/driving-scores/driving-score.html");
                intent.putExtra("topTitle", getString(R.string.driver_behavior_title));
                intent.putExtra("canGoBack", true);
                startActivity(intent);*/
//                if (ApplicationUtil.getInstance().isLogin()) {
                BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Home_SmartDriver.getStringValue());
                Boolean agreedBeavior = PreferencesUtls.getInstance(getActivity()).getBoolean(FinalConstants.SharedPreferencesConfig.AGREED_BEHAVIOR, true);
                bundle.putString("linkUrl", Constants.CURRENT_PREFIX_H5_URL + Constants.DRIVE_SCORE);
                bundle.putString("topTitle", getString(R.string.driver_behavior_title));
                bundle.putBoolean("canGoBack", true);
                bundle.putBoolean("agreedBeavior", agreedBeavior);
                new LoginUtil().loginAndActionCallBack(baseActivity, RxConstants.HOME_PAGE, this, bundle);
//                }
                //                }
                break;
            case R.id.driver_access:

                //https://idt5.onstar.com.cn/mweb/mweb-main/static/OnStar-MA7.0-h5/html/driving-scores/driving-score-demo.html
                //                if (ApplicationUtil.isGen10(getActivity())) {
               /* Intent intent = new Intent(baseActivity, CommonWebViewActivity.class);
                intent.putExtra("linkUrl", "https://idt1.onstar.com.cn/mweb/mweb-main/static/OnStar-MA7.0-h5/html/driving-scores/driving-score.html");
                intent.putExtra("topTitle", getString(R.string.driver_behavior_title));
                intent.putExtra("canGoBack", true);
                startActivity(intent);*/
                BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Home_SmartDriver.getStringValue());
                if (ApplicationUtil.getInstance().isLogin() && JoinMeConstants.OWNER.equalsIgnoreCase(ApplicationUtil.getInstance().getLoginRole())) {
                    Boolean agreedBeavior2 = PreferencesUtls.getInstance(getActivity()).getBoolean(FinalConstants.SharedPreferencesConfig.AGREED_BEHAVIOR, true);
                    bundle.putString("linkUrl", Constants.CURRENT_PREFIX_H5_URL + Constants.DRIVE_SCORE);
                    bundle.putString("topTitle", getString(R.string.driver_behavior_title));
                    bundle.putBoolean("canGoBack", true);
                    bundle.putBoolean("agreedBeavior", agreedBeavior2);
                    new LoginUtil().loginAndActionCallBack(baseActivity, RxConstants.HOME_PAGE, this, bundle);
                } else {
                    WebDataEntity entity1 = new WebDataEntity();
//                    entity1.setLinkUrl(Constants.CURRENT_PREFIX_H5_URL + Constants.DRIVE_SCORE_DEMO);
                    entity1.setLinkUrl(Constants.CURRENT_PREFIX_H5_URL + Constants.DRIVE_SCORE);
                    entity1.setTopTitle(getString(R.string.driver_behavior_title));
                    entity1.setCanGoBack(true);
                    entity1.setClzName(DriverBehaviorWebHandler.class.getName());
                    entity1.setWhat(IWebType.TYPE_DRIVER_BEHAVIOR);
                    bundle.putParcelable(IWebType.KEY_WEB_DATA, entity1);
                    bundle.putString("className", CommonWebViewActivity.class.getName());

                    if (ApplicationUtil.getInstance().isLogin()) {
                        //判断是不是访客
                        String loginRole = ApplicationUtil.getInstance().getLoginRole();
                        if (loginRole.equalsIgnoreCase(JoinMeConstants.VISITOR)) {
                            CommonWebViewActivity.launchCommonWeb(getActivity(), entity1);
                        } else {
                            try {
                                BusinessUtil.jumpActivity(bundle, this, Class.forName(bundle.getString("className")));

                            } catch (Exception e) {
                                LogManager.getInstance().e(e.getMessage());
                            }
                        }
                    } else {
                        CommonWebViewActivity.launchCommonWeb(getActivity(), entity1);
                    }
                }
                //                }
                break;
            case R.id.car_evaluate_ib:

                BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Home_CarAssessment.getStringValue());
                bundle.putString("className", com.shanghaionstar.activity.webview.handler.CommonWebViewActivity.class.getName());
                WebDataEntity entity = new WebDataEntity();
                entity.setLinkUrl(Constants.CURRENT_PREFIX_H5_URL + Constants.CAR_ASSESSMENT);
                entity.setTopTitle(getString(R.string.driver_assessment_title));
                entity.setCanGoBack(true);
                entity.setWhat(TYPE_SHARE_REPORT);
                entity.setClzName(ShareReportWebHandler.class.getName());
                bundle.putString("topTitle", getString(R.string.driver_assessment_title));
                bundle.putParcelable(IWebType.KEY_WEB_DATA, entity);
                if (ApplicationUtil.getInstance().isLogin()) {
//                    entity.setLinkUrl(Constants.CURRENT_PREFIX_H5_URL + Constants.CAR_ASSESSMENT);
                    //判断是不是访客
                    String loginRole = ApplicationUtil.getInstance().getLoginRole();
                    if (loginRole.equalsIgnoreCase(JoinMeConstants.VISITOR)) {
                        CommonWebViewActivity.launchCommonWeb(getActivity(), entity);
                    } else {
                        new LoginUtil().loginAndActionCallBack(baseActivity, RxConstants.HOME_PAGE, this, bundle);
                    }
                } else {
                    try {
                        CommonWebViewActivity.launchCommonWeb(getActivity(), entity);
//                            BusinessUtil.jumpActivity(bundle, this, Class.forName(bundle.getString("className")));

                    } catch (Exception e) {
                        LogManager.getInstance().e(e.getMessage());
                    }
                }


//                String linkUrl =  "https://idt5.onstar.com.cn/mweb/mweb-main/static/OnStar-MA7.0-h5/html/camera/open-camera.html";
//                String testUrl = "https://idt1.onstar.com.cn/mweb/mweb-main/static/OnStar-MA7.0-h5/html/ajx-question/index.html";
//                WebDataEntity entity = new WebDataEntity();
//                entity.setLinkUrl(testUrl);
//                entity.setTopTitle(getString(R.string.driver_assessment_title));
////                entity.setWhat(IWebType.TYPE_UPLOAD_IMG);
////                entity.setClzName(UploadImgWebHandler.class.getName());
//                CommonWebViewActivity.launchCommonWeb(getActivity(),entity);
//                connectToTX();
                break;
            case R.id.home_service_btn:
                BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Home_More.getStringValue());
//                Intent it = new Intent(baseActivity, com.shanghaionstar.activity.webview.handler.CommonWebViewActivity.class);
                String url = null;
                if (DeviceUtil.isChineseLanguage()) {
                    url = Constants.CURRENT_PREFIX_H5_URL + Constants.VISITORSERVICEHELP_ZH;
                } else {
                    url = Constants.CURRENT_PREFIX_H5_URL + Constants.VISITORSERVICEHELP_EN;
                }
//                Bundle mBundle = new Bundle();
                WebDataEntity mWebData = new WebDataEntity();
                mWebData.setLinkUrl(url);
                mWebData.setTopTitle(getString(R.string.h5_service_more));
//                mWebData.setCanGoBack(true);
                mWebData.setWhat(IWebType.TYPE_NORMAL);
                CommonWebViewActivity.launchCommonWeb(baseActivity, mWebData);
//                mBundle.putParcelable(IWebType.KEY_WEB_DATA,mWebData);
//                it.putExtras(mBundle);
//                it.putExtra("linkUrl", url);
//                it.putExtra("topTitle", baseActivity.getString(R.string.h5_service_more));
//                startActivity(it);
                break;
            case R.id.fuel_range:
                BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Home_FuelEconomy.getStringValue());
                WebDataEntity entity2 = new WebDataEntity();
                entity2.setLinkUrl(Constants.CURRENT_PREFIX_H5_URL + Constants.FUEL_RANGE_SUFFIX);
//                entity2.setLinkUrl("");
//                https://idt1.onstar.com.cn/mweb/mweb-main/static/OnStar-MPG-h5/html/oil_consumption.html
//                https://idt1.onstar.com.cn/mweb/mweb-main/static/OnStar-MPG-h5/html/oil_consumption.html
//                entity2.setTopTitle(getString(R.string.notify_ol_tip));
                entity2.setCanGoBack(true);
                entity2.setClzName(DriverBehaviorWebHandler.class.getName());
                entity2.setWhat(IWebType.TYPE_NORMAL);
                bundle.putParcelable(IWebType.KEY_WEB_DATA, entity2);
                bundle.putString("className", CommonWebViewActivity.class.getName());


                if (ApplicationUtil.getInstance().isLogin()) {
                    //判断是不是访客
                    String loginRole = ApplicationUtil.getInstance().getLoginRole();
                    if (loginRole.equalsIgnoreCase(JoinMeConstants.VISITOR)) {
                        CommonWebViewActivity.launchCommonWeb(getActivity(), entity2);
                    } else {
                        try {
                            BusinessUtil.jumpActivity(bundle, this, Class.forName(bundle.getString("className")));

                        } catch (Exception e) {
                            LogManager.getInstance().e(e.getMessage());
                        }
                    }
                } else {
                    CommonWebViewActivity.launchCommonWeb(getActivity(), entity2);
                }

                break;
            default:
                break;
        }
    }

//    private void setCompoundDrawableRight(int resId, TextView tv) {
//        Drawable drawable = getResources().getDrawable(resId);
//        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
//        tv.setCompoundDrawables(null, null, drawable, null);
//    }

    private void ubiAnimate() {
        float remainWidth = 24 * getResources().getDisplayMetrics().density;

        int width = ubi_ll.getWidth();
        float transX = ubi_ll.getTranslationX();
        final boolean isUbiClosed = transX < 0;
        float beginX = isUbiClosed ? -(width - remainWidth) : 0;
        final float endX = isUbiClosed ? 0 : -(width - remainWidth);
        final ObjectAnimator translation = ObjectAnimator.ofFloat(ubi_ll, "translationX", beginX, endX);
        translation.setDuration(300);
        translation.setInterpolator(new AccelerateDecelerateInterpolator());
        translation.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                if (!isUbiClosed) {
                    ubi_ib.setImageResource(R.drawable.w_ar_r);
                } else {
                    ubi_ib.setImageResource(R.drawable.w_ar_l);
                }
            }
        });
        translation.start();
    }

    private void launchToWeb() {
//        TYPE_SHARE_REPORT
        String functionID = drivingScore.getFunctionID();
        if (!TextUtils.isEmpty(functionID)) {
            BusinessUtil.sendReportByClickType(getApplication(), functionID);
        } else {
            BusinessUtil.sendReportByClickType(getApplication(), FunctionNameFindId.Home_UBISpringBar.getStringValue());
        }
        WebDataEntity entity = new WebDataEntity();
        entity.setLinkUrl(drivingScore != null && drivingScore.getLinkUrl() != null ? drivingScore.getLinkUrl() : "");
        String showInfo = drivingScore.getShowInfo();
        String reportTitle = getString(R.string.ubi_report);
        if (showInfo.contains(reportTitle.substring(reportTitle.length() - 2))) {
            entity.setTopTitle(reportTitle);
        }
        entity.setWhat(IWebType.TYPE_UPLOAD_PIC);
        entity.setClzName(UploadPicWebHandler.class.getName());
        entity.setCanGoBack(true);
        CommonWebViewActivity.launchCommonWeb(getActivity(), entity);
    }

    private void showCarInfo(boolean login) {
        if (login) {
            Vehicle vehicle = ApplicationUtil.getInstance().getCurrentVehicle();
            if (vehicle != null) {
                car_info_text_id.setText(vehicle.getMakeDesc() + " " + vehicle.getModelDesc());
            }
            if (ApplicationUtil.getInstance().getLoginRole() != null && ApplicationUtil.getInstance().getLoginRole().equalsIgnoreCase(JoinMeConstants.VISITOR)) {
//                tv_update_time.setText(R.string.home_def_update_time);
                tv_update_time.setText("---");
                tv_update.setVisibility(View.VISIBLE);
//                car_info_text_id.setText(R.string.home_def_model);
                car_info_text_id.setText("");

            }
        } else {
            car_info_text_id.setText("");
        }
    }


    public void showFloatingLayer() {
        if (floatingUtil != null)
            return;
        List<View> views = new ArrayList<>();
        views.add(driver_score);
        views.add(my_trip);
        views.add(btn__preferential_main);
        views.add(car_evaluate_ib);
        views.add(home_hot_key_layout);
        views.add(ball);
        views.add(home_hot_key_layout);
        floatingUtil = new FloatingUtil((BaseFragmentActivity) onActivity(), views);
        floatingUtil.showLayer();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (isFirstLoad()) {

            //            new SupernatantLayerLayout(onActivity()).showLayer(update_time, R.drawable.supernatant_refresh_down);
            //            showFloatingLayer(my_trip,R.drawable.floating_page2);

            ////            views ={update_time,my_trip,btn__preferential_main,update_time,my_trip,btn__preferential_main,update_time };
            //            showFloatingLayer(btn__preferential_main,R.drawable.floating_page3);
            dataRefreshPresenter = new DataRefreshPresenter(baseActivity.getScheduler(), baseActivity);
            dataRefreshPresenter.setView(this);
            setUpRefreshLayout();
            boolean hasGuide = PreferencesUtls.getInstance(onActivity()).getBoolean(Constants.FLOATING_GUIDANCE, false);
            if (!hasGuide)
                showFloatingLayer();
            ball.post(new Runnable() {
                @Override
                public void run() {
                    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) ball.getLayoutParams();
                    params.width = ball.getMeasuredHeight() * 434 / 360;
                    ball.setLayoutParams(params);
                }
            });
            ball.setLoginListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Home_LoginRegister.getStringValue());
                    Intent intent = new Intent(baseActivity, LoginActivity.class);
                    intent.putExtra(RxConstants.ACTION_NAME, RxConstants.HOME_PAGE);
                    startActivity(intent);
                }
            });

            presenter = new HomePresenter(baseActivity.getScheduler());
            presenter.setView(this);

            /**
             * 注册登录刷新页面
             */
            new LoginUtil().registLoginResult(this);
            new LoginUtil().loginAndOutShowView(baseActivity, this);
            banner_view.initBanner();
//            presenter.autoLogin();
            presenter.autoLoginWithCache();

        }
        loadBannerImage();
        //initBanner();
    }

    private void initView(Bundle bundle) {
        boolean isVisitor = false;
        ServiceItem item = optPresenter.getServiceItemByName(OptPresenter.SMART_DRIVE);
        if (ApplicationUtil.getInstance().isGen10()) {
            String loginRole = ApplicationUtil.getInstance().getLoginRole();
            boolean isOwner = !CommonUtil.isNull(loginRole) && loginRole.equalsIgnoreCase(JoinMeConstants.OWNER);
            //     isVisitor=!CommonUtil.isNull(loginRole)&& loginRole.equalsIgnoreCase(JoinMeConstants.VISITOR);
            //availability: 服务可用状态   0: 不可用(隐藏); 1: 可用(展现)
            if (isOwner && !ApplicationUtil.getInstance().isPhev() && (item != null && item.availability != null && item.availability.equalsIgnoreCase("1"))) {
//                driver_score.setVisibility(View.VISIBLE);
                //始终不可见
                driver_score.setVisibility(View.GONE);


                //          className = CommonWebViewActivity.class.getName();
            } else {
                driver_score.setVisibility(View.GONE);
                //        className = HomeFragment.class.getName();
            }
        } else {
            driver_score.setVisibility(View.GONE);
            //      className = HomeFragment.class.getName();
        }
        //    bundle.putString("className", className);
        // bundle.putBoolean("isVisitor",isVisitor);
    }


    @Override
    public void onLoadDataRefresh() {
        log.d("------------------------>>begin auto refresh<<--------------------------------");

        ball.showStatusLayout(R.drawable.status_good, getString(R.string.dignotics_status_checking), "");

//        if (refreshLayout != null) {
//            refreshLayout.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    refreshLayout.setRefreshing(true);
//                    showCarStatusAnimation();
//                    dataRefreshPresenter.doDataRefresh();
//                }
//            }, 1000);
//        }

        ptrFrameLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptrFrameLayout.autoRefresh();
            }
        }, 1000);

    }

//    private void showCarStatusAnimation(){
//        if (animationDrawable != null)
//            animationDrawable.start();
//    }

    @Override
    public void setLoading(boolean isLoading) {
    }

    @Override
    public void onResponseError(OnStarException e) {
//        if (refreshLayout != null) {
//            refreshLayout.setRefreshing(false);
        ptrFrameLayout.refreshComplete();
        if (e != null) {
//            new ToastView(baseActivity).showToast(e.getMessage());
            //判断是否从小O来的消息
            if (PreferencesUtls.getInstance(baseActivity).getBoolean(FinalConstants.SharedPreferencesConfig.IF_REFRESH_DATA_FROM_MRO, false)) {
                //判断小O回答车况界面是否切换到后台
                boolean isBackground = PreferencesUtls.getInstance(baseActivity).getBoolean(FinalConfigParams.MRO_VECHILE_ONSTOP, false);
                if (isBackground) {
                    // 消息提示
                    NotificationUtil.showNotification(baseActivity,
                            "车况刷新失败",
                            getString(R.string.get_condition_error),
                            "com.shanghaionstar.mro.CarStatusActivity");
                }
            }
        }
        ball.showStatusLayout(R.drawable.status_good, "", getString(R.string.dignotics_status_fail));
        tv_update.setVisibility(View.VISIBLE);
        tv_update_time.setText(R.string.home_refresh_failed_time);
//        }
    }

    /**
     * 如果从小O刷新的车况则提示
     */
    private void showDailogIfRefreshFromMro() {
        if (PreferencesUtls.getInstance(baseActivity).getBoolean(FinalConstants.SharedPreferencesConfig.IF_REFRESH_DATA_FROM_MRO, false)) {
            PreferencesUtls.getInstance(baseActivity).putBoolean(FinalConstants.SharedPreferencesConfig.IF_REFRESH_DATA_FROM_MRO, false);
            //避免在小O页面提示
            if (!(MyActivityManager.getInstance().getCurrentActivity() instanceof MrOActivity)
                    || (MyActivityManager.getInstance().getCurrentActivity() instanceof MrOActivity && !MyActivityManager.getInstance().getCurrentActivity().hasWindowFocus())) {

                if (!MyActivityManager.getInstance().getCurrentActivity().hasWindowFocus()
                        || !(MyActivityManager.getInstance().getCurrentActivity() instanceof MainTabActivity))
                    // 消息提示
                    NotificationUtil.showNotification(baseActivity,
                            getString(R.string.mro_refresh_vehicle_success),
                            getString(R.string.mro_refresh_vehicle_success_msg),
                            "com.shanghaionstar.mro.CarStatusActivity");
                else if (baseActivity != null && !baseActivity.isFinishing()
                        && MyActivityManager.getInstance().getCurrentActivity() instanceof MainTabActivity)
                    //弹出框操作
                    AlertDialogUtil.showOverallAlertDialog(
                            baseActivity,
                            getString(R.string.mro_refresh_vehicle_success),
                            getString(R.string.mro_refresh_vehicle_success_msg),
                            getString(R.string.check),
                            getString(R.string.cancel),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                    startActivity(new Intent(baseActivity, CarStatusActivity.class));
                                }
                            },
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                }
                            });
            }
        }
    }

    @Override
    public void onReponseSuccess(HomeModel vHomeModel) {
//        if (refreshLayout != null) {
//            refreshLayout.setRefreshing(false);
//        }

        showDailogIfRefreshFromMro();

        ptrFrameLayout.refreshComplete();

        //避免快速登录退出可能造成退出后数据仍显示问题
        if (!ApplicationUtil.getInstance().isLogin())
            return;

        if (vHomeModel != null) {
            if (vHomeModel.ball_img_res != 0) {
                ball.showStatusLayout(vHomeModel.ball_img_res, vHomeModel.statusRate, vHomeModel.statusRateDesc);
            }
            if (!CommonUtil.isNull(vHomeModel.tv_oil_value)) {
                tv_oil_value.setText(vHomeModel.tv_oil_value);
            }
            if (!CommonUtil.isNull(vHomeModel.tv_mile_value)) {
                tv_mile_value.setText(vHomeModel.tv_mile_value);
            }
            if (!CommonUtil.isNull(vHomeModel.showTime)) {
                tv_update_time.setText(vHomeModel.showTime);
                tv_update.setVisibility(View.VISIBLE);
            }

            //            fuel_meter.playAnimator(vHomeModel.fuelDegree);
//            fuel_meter.playAnimator(50);
            fuel_meter.playAnimator(vHomeModel.fuel_value / 100);
            //            fuel_meter.playAnimator(99);

            ball.showStatusLayout(vHomeModel.ball_img_res, vHomeModel.statusRate, vHomeModel.statusRateDesc);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        presenter.getShortCuts();
        presenter.showMro();
        sendToCar();
        gotoDriveScore();
        resetSocreOnAgreementOffSate();
        getCarAssessmentStatus();
        hideDriveScoreViewOnLoginOff();
        //test
//        RemoteModel remoteModel = new RemoteModel.Builder().setRemoteCommandsType(RemoteCommandsType.COMMANDS_ALERT).create();
//        PinDialogFragment pinDialogFragment = PinDialogFragment.newInstance(remoteModel.getRemoteCommandsType(), RxConstants.REMOTE_PAGE);
//        pinDialogFragment.show(getFragmentManager(), "pin_dialog");

    }

    /**
     * 获取车况报告分享协议状态
     */
    private void getCarAssessmentStatus() {
        String loginRole = ApplicationUtil.getInstance().getLoginRole();
        boolean isOwner = !CommonUtil.isNull(loginRole) && loginRole.equalsIgnoreCase(JoinMeConstants.OWNER);
        if (ApplicationUtil.getInstance().isLogin() && isOwner && ApplicationUtil.getInstance().getServiceItems() == null) {
            getOptPresenter().getServiceStatus(getActivity());
        }
    }

    /**
     * 未登录不显示驾驶评分
     */
    private void hideDriveScoreViewOnLoginOff() {
        if (!ApplicationUtil.getInstance().isLogin()) {
            driver_score.setVisibility(View.GONE);
            ubi_ll.setVisibility(View.GONE);
        }
    }

    /**
     * 若是服务评价协议关闭状态则重置
     */
    private void resetSocreOnAgreementOffSate() {
        ServiceItem item = getOptPresenter().getServiceItemByName(OptPresenter.SMART_DRIVE);
        if (ApplicationUtil.getInstance().isGen10()) {
            String loginRole = ApplicationUtil.getInstance().getLoginRole();
            boolean isOwner = !CommonUtil.isNull(loginRole) && loginRole.equalsIgnoreCase(JoinMeConstants.OWNER);
            //availability: 服务可用状态   0: 不可用(隐藏); 1: 可用(展现)
            if (isOwner && !ApplicationUtil.getInstance().isPhev() && (item != null && item.availability != null && item.availability.equalsIgnoreCase("1"))) {
                if (!PreferencesUtls.getInstance(getActivity()).getBoolean(FinalConstants.SharedPreferencesConfig.AGREED_BEHAVIOR, false)) {
                    driver_score.reset();
                    ubi_ll.setVisibility(View.GONE);
                } else if (this.drivingScore != null)
                    showDrivingScore(this.drivingScore);
            }
        }
    }

    /***
     * 高德地图poi发送到车 分割线
     ***/
    private void sendToCar() {
        if (poiItemInfoBundle != null) {
            BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Home_MyTrip.getStringValue());
            Intent intent = new Intent(baseActivity, NavActivity.class);
            Bundle bundle = new Bundle();
            bundle.putAll(poiItemInfoBundle);
            intent.putExtras(bundle);
            startActivity(intent);
            poiItemInfoBundle = null;
        }
    }

    private void gotoDriveScore() {
        if (driveScoreEntity != null) {
            Bundle bundle = new Bundle();
            Boolean agreedBeavior = PreferencesUtls.getInstance(getActivity()).getBoolean(FinalConstants.SharedPreferencesConfig.AGREED_BEHAVIOR, true);
            bundle.putString("linkUrl", driveScoreEntity.getLinkUrl());
            bundle.putString("topTitle", getString(R.string.driver_behavior_title));
            bundle.putBoolean("canGoBack", true);
            bundle.putBoolean("agreedBeavior", agreedBeavior);
            new LoginUtil().loginAndActionCallBack(baseActivity, RxConstants.HOME_PAGE, this, bundle);
        }
    }

    Bundle poiItemInfoBundle;

    public void setArgument(Bundle bundle) {
        this.poiItemInfoBundle = bundle;
    }

    WebDataEntity driveScoreEntity;

    public void setDriveScoreEntity(WebDataEntity driveScoreEntity) {
        this.driveScoreEntity = driveScoreEntity;
    }

    /***
     * 高德地图poi发送到车 分割线
     ***/

    @Override
    public Activity onActivity() {
        return getActivity();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (dataRefreshPresenter != null) {
            dataRefreshPresenter.unRegisterSubscriber();
            dataRefreshPresenter = null;
        }
    }

    public boolean isChevrolet() {
//        (desc.contains("雪佛兰") || desc.toLowerCase().contains("Chevrolet".toLowerCase()))
        Vehicle vehicle = ApplicationUtil.getInstance().getCurrentVehicle();
        if (vehicle == null)
            return false;
        String desc = vehicle.getModelDesc();
        return desc.contains("雪佛兰") || desc.toLowerCase().contains("Chevrolet".toLowerCase());
    }

    @Override
    public void onLogin(final Bundle bundle, String resultCode) {
        if ((RxConstants.ACTION_SUCCESS).equals(resultCode)) {
            //            ball.disableLoginLayout("登录成功!");
            initView(bundle);
            if (bundle != null) {
                if (getString(R.string.driver_behavior_title).equals(bundle.getString("topTitle"))) {
                    String loginRole = ApplicationUtil.getInstance().getLoginRole();
                    if (!CommonUtil.isNull(loginRole) && loginRole.equalsIgnoreCase(JoinMeConstants.VISITOR)) {
                        showUpgradeDia();
                    } else {
                        if (!bundle.getBoolean("agreedBeavior")) {
                            showAgreeDialog(bundle);
                        } else {
                            /**
                             * t+1,t+n话术弹框
                             */
                            String firstInfo = PreferencesUtls.getInstance(getActivity()).getString((FinalConstants.SharedPreferencesConfig.ISFIRSTINFO + ApplicationUtil.getInstance().getIdpID()
                                    + ApplicationUtil.getInstance().getVin()));
                            if (CommonUtil.isNull(firstInfo)) {
                                firstInfo = "y";
                            }
                            LogManager.getInstance().d("firstInfo------>>" + firstInfo);
                            bundle.putString("firstInfo", firstInfo);
                            WebDataEntity entity1 = new WebDataEntity();
                            entity1.setLinkUrl(Constants.CURRENT_PREFIX_H5_URL + Constants.DRIVE_SCORE);
                            entity1.setTopTitle(getString(R.string.driver_behavior_title));
                            entity1.setCanGoBack(true);
                            entity1.setClzName(DriverBehaviorWebHandler.class.getName());
                            entity1.setWhat(IWebType.TYPE_DRIVER_BEHAVIOR);
                            bundle.putParcelable(IWebType.KEY_WEB_DATA, entity1);
                            bundle.putString("className", CommonWebViewActivity.class.getName());

                            if (!"e".equals(firstInfo)) {
                                PreferencesUtls.getInstance(getActivity()).putString(
                                        (FinalConstants.SharedPreferencesConfig.ISFIRSTINFO + ApplicationUtil.getInstance().getIdpID()
                                                + ApplicationUtil.getInstance().getVin()), "e");//e表示第1+次打开；y代表第1次打开；n代表设置里关闭再打开
                            }
                        }
                    }
                } else if (getString(R.string.function_go_home).equals(bundle.getString("title")) || getString(R.string.function_go_company).equals(bundle.getString("title"))) {
//                    UserAddressInfoImpl mUserAddressInfoImpl = new UserAddressInfoImpl(baseActivity);
//                    List list = mUserAddressInfoImpl.getAll();
////                    list = null;
//                    if (list == null || list.size() == 0) {
//                        showGoHomeOrCompanyDialog(bundle.getString("title"), bundle);
//                        return;
//                    }
                    String funcTitle = bundle.getString("title");
                    if (getString(R.string.function_go_company).equalsIgnoreCase(funcTitle)) {
                        if (checkAddr("2", funcTitle)) return;
                    } else if (getString(R.string.function_go_home).equalsIgnoreCase(funcTitle)) {
                        if (checkAddr("1", funcTitle)) return;
                    }
                } else if (getString(R.string.sc_brand_club).equals(bundle.getString("title"))) {
//                    Intent intentWeb = new Intent(getActivity(), CommonWebViewActivity.class);
//                    Bundle bun = new Bundle();
//                    bun.putString("topTitle", bundle.getString("title"));
////                    String encryptUrl = EncryptUtil.encryptBase64(getActivity(),"http://cadillac-club.mysgm.com.cn/touch/control/home");
////                    Log.e("url",encryptUrl);
//                    String url = EncryptUtil.decryptBase64(getActivity(),Constants.CADILLAC_CLUB_URL);
//                    bun.putString("linkUrl",url);
//                    intentWeb.putExtras(bun);
//                    startActivity(intentWeb);
                    WebDataEntity entity = new WebDataEntity();
                    entity.setTopTitle(bundle.getString("title"));
                    entity.setCanGoBack(true);
                    String encryptUrl = isChevrolet() ? Constants.CHEVROLET_CLUB_URL : EncryptUtil.decryptBase64(getActivity(), Constants.CADILLAC_CLUB_URL);
                    entity.setLinkUrl(encryptUrl);
                    CommonWebViewActivity.launchCommonWeb(getActivity(), entity);
                    return;
                } else if (getString(R.string.sc_buy_pack).equals(bundle.getString("title"))) {
                    bundle.putSerializable("packageType", PackageType.CORE);
                    bundle.putString("from", "ShortCut");
                }
                if (getString(R.string.driver_assessment_title).equals(bundle.getString("topTitle"))) {
                    ServiceItem item = getOptPresenter().getServiceItemByName(OptPresenter.CAR_ASSESSMENT);
                    String loginRole = ApplicationUtil.getInstance().getLoginRole();
                    boolean isOwner = !CommonUtil.isNull(loginRole) && loginRole.equalsIgnoreCase(JoinMeConstants.OWNER);
                    if (isOwner && ServiceItem.isCarAssessClosed(item)
                            && !PreferencesUtls.getInstance(getContext()).getBoolean(FinalConstants.SharedPreferencesConfig.HAS_SHOWED_CARASSESSMENT_DIALOG + new DeviceUtil(getContext()).getAppVersionCode(), false)) {
                        showCarAssDialog(bundle);
                        PreferencesUtls.getInstance(getContext()).putBoolean(FinalConstants.SharedPreferencesConfig.HAS_SHOWED_CARASSESSMENT_DIALOG + new DeviceUtil(getContext()).getAppVersionCode(), true);
                    } else {
                        try {
                            BusinessUtil.jumpActivity(bundle, this, Class.forName(bundle.getString("className")));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    try {
                        BusinessUtil.jumpActivity(bundle, this, Class.forName(bundle.getString("className")));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private CarAssessAgreementDialog carAssessAgreementDialog;

    private void showCarAssDialog(final Bundle bundle) {
        if (carAssessAgreementDialog == null) {
            carAssessAgreementDialog = new CarAssessAgreementDialog(getContext());
            carAssessAgreementDialog.setCarAssessmentAgreeListener(new CarAssessAgreementDialog.carAssessmentAgreeListener() {
                @Override
                public void doOnAgree() {
                    carAssessAgreementDialog.dismiss();
                    try {
                        BusinessUtil.jumpActivity(bundle, HomeFragment.this, Class.forName(bundle.getString("className")));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        carAssessAgreementDialog.show();
    }


    private boolean isContainType(List<UserAddressEntity> list, String type) {
        for (UserAddressEntity entity : list) {
            String cate = entity.getCustomerCatetory();
            String userId = entity.getUserId();
            if (cate.equalsIgnoreCase(type) && ApplicationUtil.getInstance().getIdpID().equals(userId)) {
                return true;
            }
        }
        return false;
    }

    private boolean checkAddr(String cate, String title) {
        UserAddressInfoImpl mUserAddressInfoImpl = new UserAddressInfoImpl(baseActivity);
        List<UserAddressEntity> list = mUserAddressInfoImpl.getAll();
        if (list == null || list.size() == 0 || !isContainType(list, cate)) {
            Bundle bundle = new Bundle();
            bundle.putString("title", title);
            showGoHomeOrCompanyDialog(title, bundle);
            return true;
        }
        return false;
    }

    private void showGoHomeOrCompanyDialog(final String msg, final Bundle bundle) {
        AlertDialogUtil.showAlertDialog(baseActivity, getString(R.string.dialog_warning),
                getString(R.string.nav_home_comp_set, msg), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            BusinessUtil.jumpActivity(bundle, HomeFragment.this, NavActivity.class);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
    }

    @Override
    public void onShowShortCuts(List<ItemViewData> itemViews) {
        CustomLayoutsGroup group = new CustomLayoutsGroup(onActivity());
        home_hot_key_layout.removeAllViews();
        group.customShortCutsLayoutGroup(home_hot_key_layout, itemViews);
        final String[] remoteStrList = getResources().getStringArray(R.array.remote_control_list);
        group.setOnViewItemClickListener(new CustomLayoutsGroup.OnViewItemClickListener() {
            @Override
            public boolean onViewItemClick(ItemViewData item) {
                String functionValue = item.getFunctionValue();
                if (!TextUtils.isEmpty(functionValue) && !functionValue.equalsIgnoreCase(FunctionNameFindId.UnSend.getStringValue())) {
                    BusinessUtil.sendReportByClickType(getActivity(), functionValue);
                }
                //远程控制功能
                if (remoteControl(item, remoteStrList)) return false;
                if (item.getText().equalsIgnoreCase(getString(R.string.nav_more_search))) {
                    BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Quickly_More.getStringValue());
//                    if (ApplicationUtil.getInstance().isLogin())
                    return true;
//                    return false;
                }
                if (item.getText().equalsIgnoreCase(getString(R.string.ele_fence))) {
                    if (!BusinessUtil.checkPackageRight(Constants.ENTITLEMENT_M08SAFETY_ZONE, getActivity(), true)) {
                        return false;
                    }
                }
                if (item.getText().equalsIgnoreCase(getString(R.string.assistant_connect))) {
                    AlertDialogUtil.showAlertDialog(getActivity(), getString(R.string.dialog_warning), getString(R.string.connect_phone), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            requestRunTimePermissions(new String[]{Manifest.permission.CALL_PHONE}, new PermissionCall() {
                                @Override
                                public void requestSuccess() {
                                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + getString(R.string.connect_phone)));
                                    startActivity(intent);
                                }

                                @Override
                                public void refused() {

                                }
                            });
                        }
                    }, true);
                    return false;
                }
                if (item.getText().equalsIgnoreCase(getString(R.string.function_poi_search))) {
                    return true;
                }
//                Bundle bundle = new Bundle();
                Bundle bundle = item.getBundle();
                bundle.putString("className", item.getClassName());
                bundle.putString("title", item.getText());
                bundle.putString("topTitle", "shortcuts");
                item.setBundle(bundle);
                new LoginUtil().loginAndActionCallBack(getActivity(), RxConstants.HOME_PAGE, HomeFragment.this, item.getBundle());
                return false;
            }
        });
    }

    private boolean remoteControl(ItemViewData item, String[] remoteStrList) {
        String itemTitle = item.getText();
        int N = remoteStrList.length;
        for (int i = 0; i < N; i++) {
            String title = remoteStrList[i];
            if (itemTitle.equalsIgnoreCase(title)) {
                if (baseActivity instanceof MainTabActivity) {
                    ((MainTabActivity) baseActivity).remoteControlFromShortcut(i);
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void showBallLoadingMsg(String msg) {

    }

    @Override
    public void onLogin() {
        //根据是否pehv车辆显示油表电力图标
        fuel_meter.updateByCarType(ApplicationUtil.getInstance().isPhev());
        presenter.showMro();
        presenter.getShortCuts();
        showCarInfo(true);
        /**
         * 访客更多服务
         */
        loadBannerImage();
        showRefreshNotification();
        showServiceBtn(true);
        showIsPhevFuelTxt(true);
        ptrFrameLayout.refreshComplete();
        if (JoinMeConstants.VISITOR.equalsIgnoreCase(ApplicationUtil.getInstance().getLoginRole())) {
            ball.showStatusLayout(R.drawable.status_good, getString(R.string.vehicle_title), "———");
//            ball.showStatusLayout(R.drawable.status_good, getString(R.string.dignotics_status_excellent), getString(R.string.dignotics_status_keep_on));
//            tv_oil_value.setText(R.string.home_default_oil_value);
//            tv_mile_value.setText(R.string.home_default_mile_value);
//            fuel_meter.playAnimator((float) (40.0 / 100.0));
//            refreshLayout.setEnabled(false);
            ptrFrameLayout.setEnabled(false);
            fuel_meter.updateByCarType(true);
        } else {
//            refreshLayout.setEnabled(true);
            ptrFrameLayout.setEnabled(true);
            dataRefreshPresenter.getHistoryOVD();
//            if (ApplicationUtil.getInstance().isPhev()) {
//                driver_score.setVisibility(View.GONE);
//            }
//            else {
//                loadDrivingScore();
//            }
            presenter.getServiceStatus();
        }
        ball.setStatusListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("className", CarManageActivity.class.getName());
                bundle.putString("topTitle", "my_car");
                new LoginUtil().loginAndActionCallBack(baseActivity, RxConstants.HOME_PAGE, HomeFragment.this, bundle);
                BusinessUtil.sendReportByClickType(baseActivity, FunctionNameFindId.Home_VehicleStatus.getStringValue());
            }
        });

        //车主生活中车检日期提醒相关功能：获取行驶证日期并设置预约提醒日期
        new VehicleInspectionManager((BaseActivity) onActivity()).getDrivingLicenseDate();

        main_container.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Home_ClickMrO.getStringValue());
                Intent intent = new Intent(getActivity(), MrOActivity.class);
                getActivity().startActivityForResult(intent, Constants.MAIN_TO_MRO);
                getApplication().setMroForeground(true);
            }
        });


//        Intent it = getActivity().getIntent();
//
//        if(it!=null && it.getStringExtra("receiveType") !=null && it.getStringExtra("receiveType").equals("100")){
//            WebDataEntity entity = new WebDataEntity();
//            entity.setLinkUrl(it.getStringExtra("uri"));
//            entity.setCanGoBack(true);
//            CommonWebViewActivity.launchCommonWeb(getActivity(), entity);
//        }

        //短信进去自动登录后跳转
        String receiveType = ((MainTabActivity) getActivity()).receiveType;
        if (receiveType != null && (receiveType.equalsIgnoreCase("100") || receiveType.equalsIgnoreCase(NotificationConstants.B2C_RECEIVETYPE_DRIVINGSCORE))) {
            String url = getActivity().getIntent().getStringExtra("uri");
            WebDataEntity entity = new WebDataEntity();
            entity.setLinkUrl(url);
            String title = getActivity().getIntent().getStringExtra("title");
            if (!TextUtils.isEmpty(title))
                entity.setTopTitle(title);
            entity.setCanGoBack(true);
            CommonWebViewActivity.launchCommonWeb(getActivity(), entity);
            ((MainTabActivity) getActivity()).receiveType = "";
        }
    }

    private void loadDrivingScore() {
        if (ApplicationUtil.getInstance().isLogin()
                && !TextUtils.isEmpty(ApplicationUtil.getInstance().getVin()))
            dataRefreshPresenter.loadDrivingScore();
    }

    @Override
    public void showLoadDrivingScoreErr(Throwable throwable) {
//        new ToastView(getContext()).showRemoteToast(getResources().getString(R.string.loading_driving_score_failed));
    }

    private void showIsPhevFuelTxt(boolean isLogin) {
        String loginRole = ApplicationUtil.getInstance().getLoginRole();
        boolean isVisitor = loginRole != null && loginRole.equalsIgnoreCase(JoinMeConstants.VISITOR);
        if (isLogin && !isVisitor) {
            if (ApplicationUtil.getInstance().isPhev()) {
                tv_fuel.setText(getString(R.string.home_phev_tv));
            } else {
                tv_fuel.setText(getString(R.string.home_fuel_tv));
            }
        } else {
            tv_fuel.setText(getString(R.string.home_phev_tv));
        }
    }

    private void showServiceBtn(boolean isLogin) {
        if (isLogin) {
            if (JoinMeConstants.VISITOR.equalsIgnoreCase(ApplicationUtil.getInstance().getLoginRole())
                    && DeviceUtil.isChineseLanguage()) {
                home_service_btn.setVisibility(View.VISIBLE);
                if (PreferencesUtls.getInstance(getActivity()).getBoolean(ApplicationUtil.getInstance().getIdpID(), true)) {
                    PreferencesUtls.getInstance(getActivity()).putBoolean(ApplicationUtil.getInstance().getIdpID(), false);
                    home_service_btn.performClick();
                }
            } else {
                home_service_btn.setVisibility(View.GONE);
            }
        } else {
            home_service_btn.setVisibility(View.VISIBLE);
        }
    }

    private boolean isShowFloat = false;

    @Override
    public void onLoginOut() {
        notLogin();
    }

    @Override
    public void notLogin() {
        ball.showLoginLayout(baseActivity.getString(R.string.ball_login));
        fuel_meter.updateByCarType(true);
        fuel_meter.playAnimator(0f);
        showCarInfo(false);
        showServiceBtn(false);
        showIsPhevFuelTxt(false);
        ball.showLoginLayout(getResources().getString(com.onstar.cn.weight.R.string.ball_login));
        tv_oil_value.setText(R.string.home_default_value);
        tv_mile_value.setText(R.string.home_default_value);
        tv_update_time.setText("");
        tv_update.setVisibility(View.GONE);
        ptrFrameLayout.setEnabled(false);
        ptrFrameLayout.refreshComplete();
//        refreshLayout.setEnabled(false);
//        refreshLayout.setRefreshing(false);
        drivingScore = null;
        driver_score.setVisibility(View.GONE);
        ubi_ll.setVisibility(View.GONE);
        driver_score.reset();
        ball.setStatusListener(null);
//        getApplication().setItem(null);
        ApplicationUtil.getInstance().setServiceItems(null);
//        getApplication().setCarAssessStatusItem(null);
//        isAutoLogin();
//        if (!isShowFloat) {
//            isShowFloat = true;
//            ptrFrameLayout.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//
//                }
//            }, 500);
//        }
    }

    @Override
    public void isAutoLogin() {
        ball.showAutoLogin();
    }



/*    private void loadBannerImage() {
        if (BusinessUtil.getConfigValue(FinalConfigParams.UPDATE_BANNER, getActivity()).equals(FinalConfigParams.TRUE)) {
            banner_view.loadDatas(dot_layout);
            //			banner_view.setStateListener(this);
            BusinessUtil.updateConfigValue(FinalConfigParams.UPDATE_BANNER, FinalConfigParams.FALSE, getActivity());
        }
    }*/

    private void loadBannerImage() {
        if (PreferencesUtls.getInstance(getActivity()).getBoolean(FinalConfigParams.UPDATE_BANNER, true)) {
            presenter.commandData();
            BusinessUtil.updateConfigValue(FinalConfigParams.UPDATE_BANNER, FinalConfigParams.FALSE, getActivity());
        }
    }

    private DrivingScore drivingScore;

    @Override
    public void showDrivingScore(DrivingScore drivingScore) {
        this.drivingScore = drivingScore;
        if (drivingScore != null && !CommonUtil.isNull(drivingScore.getScore())) {
            driver_score.playAnimator(
                    Float.parseFloat(drivingScore.getScore())
                    , (int) Float.parseFloat(drivingScore.getScore()));
            if (!TextUtils.isEmpty(drivingScore.getShowInfo())) {
                ubi_ll.setVisibility(View.VISIBLE);
                ubi_tv.setText(Html.fromHtml(drivingScore.getShowInfo()));
                ubi_tv.setSelected(true);
            } else {
                ubi_ll.setVisibility(View.GONE);
            }
        }
    }


    private void setUpRefreshLayout() {
//        refreshLayout.setTargetScrollWithLayout(true);
//        View head = LayoutInflater.from(baseActivity).inflate(R.layout.head_carstatus_loading, refreshLayout, false);
//        refreshLayout.setHeaderView(head);
//        ImageView img_loading = (ImageView) head.findViewById(R.id.img_loading);
//        animationDrawable = (AnimationDrawable) img_loading.getDrawable();
//        refreshLayout.setOnPullRefreshListener(refreshLayout.new OnPullRefreshListenerAdapter() {
//            @Override
//            public void onRefresh() {
//                animationDrawable.start();
//                dataRefreshPresenter.doDataRefresh();
//            }
//        });
//        refreshLayout.setEnabled(ApplicationUtil.getInstance().isLogin());
//        refreshLayout.setRefreshing(ApplicationUtil.getInstance().isLogin());

        OnStarPtrHeader header = new OnStarPtrHeader(baseActivity);
        ptrFrameLayout.setHeaderView(header);
        ptrFrameLayout.addPtrUIHandler(header);
        ptrFrameLayout.setBackgroundColor(ContextCompat.getColor(baseActivity, R.color.white));
        ptrFrameLayout.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                tv_update.setVisibility(View.GONE);
                tv_update_time.setText(R.string.home_refresh_des);
                hideRefreshNotification();
                ball.showStatusLayout(R.drawable.status_good, getString(R.string.dignotics_status_checking), "");
                dataRefreshPresenter.doDataRefresh();
                if (ApplicationUtil.getInstance().getServiceItems() == null && ApplicationUtil.getInstance().isLogin()) {
                    getOptPresenter().getServiceStatus(getActivity());
                }
            }
        });
        ptrFrameLayout.setEnabled(ApplicationUtil.getInstance().isLogin());
    }

    private void hideRefreshNotification() {
        Observable.timer(5000, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {
                        if (PreferencesUtls.getInstance(getActivity()).getBoolean(FinalConstants.SharedPreferencesConfig.IF_NOTIFIY_VEHICLE_REFRESH + new DeviceUtil(getContext()).getAppVersionCode(), true)) {
                            PreferencesUtls.getInstance(getActivity()).putBoolean(FinalConstants.SharedPreferencesConfig.IF_NOTIFIY_VEHICLE_REFRESH + new DeviceUtil(getContext()).getAppVersionCode(), false);
                            com.shanghaionstar.weight.ToastView.hideToast(main_container);
                        }
                    }
                });
    }

    /**
     * 升级为车主
     */
    private void showUpgradeDia() {
        AlertDialogUtil.showAlertDialog(getActivity(), R.string.dialog_warning, R.string.SB021_MSG013,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        JoinMeUtils.checkVisitor(HomeFragment.this);
                    }
                }, true, R.string.upgrade_to_owner);
    }

    AgreementDialog agreementDialog;
    OptPresenter optPresenter;

    private void showLoadingDialog() {
        dialog = showLoadProgress();
        dialog.show();
    }

    public OptPresenter getOptPresenter() {
        if (optPresenter == null) {
            optPresenter = new OptPresenter(baseActivity.getScheduler(), baseActivity);
            optPresenter.setOptView(new IOptViewImpl() {
                @Override
                public void onTurnOnSuccess(BaseResponse response, Bundle bundle) {
                    BusinessUtil.sendReportByRequestParams(getContext(), FunctionNameFindId.SmartDriver_HomeAgree.getStringValue(), ReportReqParam.getSmartDriveSettingReqParam(FunctionNameFindId.SmartDriver_HomeAgree, true));
                    PreferencesUtls.getInstance(getActivity()).putBoolean(FinalConstants.SharedPreferencesConfig.AGREED_BEHAVIOR, true);
                    try {
                        bundle.putString("firstInfo", "n");
                        WebDataEntity entity = new WebDataEntity();
                        entity.setLinkUrl(Constants.CURRENT_PREFIX_H5_URL + Constants.DRIVE_SCORE);
                        entity.setTopTitle(getString(R.string.driver_behavior_title));
                        entity.setCanGoBack(true);
                        entity.setClzName(DriverBehaviorWebHandler.class.getName());
                        entity.setWhat(IWebType.TYPE_DRIVER_BEHAVIOR);
                        bundle.putParcelable(IWebType.KEY_WEB_DATA, entity);
                        bundle.putString("className", CommonWebViewActivity.class.getName());
                        BusinessUtil.jumpActivity(bundle, HomeFragment.this, Class.forName(bundle.getString("className")));
                        PreferencesUtls.getInstance(getActivity()).putString(
                                (FinalConstants.SharedPreferencesConfig.ISFIRSTINFO + ApplicationUtil.getInstance().getIdpID()
                                        + ApplicationUtil.getInstance().getVin()), "e");//e表示第1+次打开；y代表第1次打开；n代表设置里关闭再打开
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                        PreferencesUtls.getInstance(getActivity()).putString(
                                (FinalConstants.SharedPreferencesConfig.ISFIRSTINFO + ApplicationUtil.getInstance().getIdpID()
                                        + ApplicationUtil.getInstance().getVin()), "n");//e表示第1+次打开；y代表第1次打开；n代表设置里关闭再打开
                    }
                    dismissDialog(dialog);
                }

                @Override
                public void onFailed(Throwable throwable) {
                    dismissDialog(dialog);
                    BusinessUtil.sendReportByRequestParams(getContext(), FunctionNameFindId.SmartDriver_HomeAgree.getStringValue(), ReportReqParam.getSmartDriveSettingReqParam(FunctionNameFindId.SmartDriver_HomeAgree, false, throwable == null ? "" : throwable.getMessage()));
                    if (throwable != null && !TextUtils.isEmpty(throwable.getMessage())) {
                        new ToastView(baseActivity).showToast(throwable.getMessage());
                    }
                }

//                @Override
//                public void onGetServiceItem(List<ServiceItem> item) {
//                    super.onGetServiceItem(item);
//
//                }
            });
        }
        return optPresenter;
    }

    private void showAgreeDialog(final Bundle bundle) {
        if (agreementDialog == null) {
            agreementDialog = new AgreementDialog(baseActivity);
            agreementDialog.setCancelListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PreferencesUtls.getInstance(getActivity()).putBoolean(FinalConstants.SharedPreferencesConfig.AGREED_BEHAVIOR, false);
                    agreementDialog.dismiss();
                    WebDataEntity entity1 = new WebDataEntity();
                    entity1.setLinkUrl(Constants.CURRENT_PREFIX_H5_URL + Constants.DRIVE_SCORE);
                    entity1.setTopTitle(getString(R.string.driver_behavior_title));
                    entity1.setCanGoBack(true);
                    entity1.setClzName(DriverBehaviorWebHandler.class.getName());
                    entity1.setWhat(IWebType.TYPE_DRIVER_BEHAVIOR);
                    CommonWebViewActivity.launchCommonWeb(getActivity(), entity1);
                }
            });
            agreementDialog.setConfirmListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    agreementDialog.dismiss();
                    showLoadingDialog();
                    getOptPresenter().turnOn(bundle);
                }
            });
        }
        if (baseActivity != null && !baseActivity.isFinishing())
            agreementDialog.show();
    }


    @Override
    public void showCommandInProgress() {
//        if (refreshLayout != null) {
//            refreshLayout.setRefreshing(false);
//        }
        ptrFrameLayout.refreshComplete();
        ball.showStatusLayout(R.drawable.status_good, getString(R.string.dignotics_status_checking), "");
    }

    @Override
    public void showViewByRole(String role) {
//        if(JoinMeConstants.OWNER.equalsIgnoreCase(role)) {
//
//        }else if(JoinMeConstants.VISITOR.equalsIgnoreCase(role)) {
//
//        }else if(JoinMeConstants.DRIVER.equalsIgnoreCase(role)) {
//
//        }else if(JoinMeConstants.PROXY.equalsIgnoreCase(role)) {
//
//        }
    }

    @Override
    public void showUpgrade(final OnStarException e) {
        AlertDialogUtil.showAlertDialog(baseActivity, R.string.E9004,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (!CommonUtil.isNull(e.getMessage())) {
                            Intent intent = new Intent("android.intent.action.VIEW");
                            log.d("upgrade mandatory uri is ------------------------> " + e.getMessage());
                            intent.setData(Uri.parse(e.getMessage()));
                            startActivity(intent);
                        } else {
                            dialog.dismiss();
                        }
                    }
                }, null);
    }

    @Override
    public void showMro(boolean isShow) {
        if (isShow) {
            main_container.showMro(true);
            main_container.refreshMroFigure();
        } else {
            main_container.showMro(false);
        }
    }

    @Override
    public void showSmartDriver(boolean isShow) {
//        driver_score.setVisibility(isShow ? View.VISIBLE : View.GONE);
        //始终不可见
        driver_score.setVisibility(View.GONE);
//        ubi_ll.setVisibility(isShow?View.VISIBLE:View.GONE);
        if (isShow)
            loadDrivingScore();
    }

    @Override
    public void onShowBanner(List<ResponBannerEntity> bannerEntities) {
        //缓存banner，用于查看维修保养建议
        getApplication().setBannerEntities(bannerEntities);
        if (CommonUtil.isNull(bannerEntities)) {
            banner_view.initBanner();
        } else {
            final DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.drawable.home_banner_failed)
                    .showImageForEmptyUri(R.drawable.home_banner_failed).showImageOnFail(R.drawable.home_banner_failed)
                    .resetViewBeforeLoading(true).cacheInMemory(true).cacheOnDisc(false).imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
                    .bitmapConfig(Bitmap.Config.RGB_565).displayer(new FadeInBitmapDisplayer(100)).build();
            if (bannerEntities != null && bannerEntities.size() == 1) {
                final ResponBannerEntity entity = bannerEntities.get(0);
                banner_view.setVisibility(View.GONE);
                banner_iv.setVisibility(View.VISIBLE);
                ImageLoader.getInstance().displayImage(entity.getImgUrl(), banner_iv, options);
                banner_iv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        presenter.bannerClick(entity);
                    }
                });
                return;
            } else {
                banner_iv.setVisibility(View.GONE);
                banner_view.setVisibility(View.VISIBLE);
                banner_view.setImageResources(bannerEntities, new ImageCycleView.ImageCycleViewListener() {
                    @Override
                    public void displayImage(Object o, ImageView imageView) {
                        ResponBannerEntity entity = (ResponBannerEntity) o;
                        ImageLoader.getInstance().displayImage(entity.getImgUrl(), imageView, options);
                    }

                    @Override
                    public void onImageClick(Object o, int position, View imageView) {
                        presenter.bannerClick((ResponBannerEntity) o);
                    }
                });
            }
        }
    }

    @Override
    public void onBehindGetData(int state) {
        switch (state) {
            case CACHE_STATE_NOCACHE:
                ball.showLoginLayout(baseActivity.getString(R.string.ball_login));
                break;
//            case CACHE_STATE_EXPIRED:
//                onLogin();
//                break;
//            case CACHE_STATE_NORMAL:
//                onLogin();
//                break;
        }

    }

    private void showRefreshNotification() {
        String loginRole = ApplicationUtil.getInstance().getLoginRole();
        boolean isNotVisitor = !JoinMeConstants.VISITOR.equalsIgnoreCase(loginRole);
        if (ApplicationUtil.getInstance().isLogin()
                && isNotVisitor
                && PreferencesUtls.getInstance(getActivity()).getBoolean(FinalConstants.SharedPreferencesConfig.IF_NOTIFIY_VEHICLE_REFRESH + new DeviceUtil(getContext()).getAppVersionCode(), true)) {
            com.shanghaionstar.weight.ToastView.showToast(main_container, R.string.notify_pull_to_refresh);
        } else {
            com.shanghaionstar.weight.ToastView.hideToast(main_container);
        }
    }

//    private void connectToTX() {
//
//        IWXAPI api = WXAPIFactory.createWXAPI(getActivity(), "gh_97841e6a5434", true);
//        IWXAPI api = WXAPIFactory.createWXAPI(getActivity(), PayMeConstants.APP_ID, true);
//        // 将应用的appid注册到微信
////        api.registerApp(PayMeConstants.APP_ID);
//        api.registerApp("gh_97841e6a5434");
//        JumpToBizProfile.Req req  = new JumpToBizProfile.Req();
////        req.toUserName = "gh_a907e73c1fb2";
//        req.toUserName = "wx6a20b78a6109d40a";
//        req.profileType = JumpToBizProfile.JUMP_TO_NORMAL_BIZ_PROFILE;
//        req.extMsg = "extMsg";
//        api.sendReq(req);
//    }


}